package com.example.demo.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.*;
import java.util.List;

public class CCEngineUtill {
    private static final Logger logger = LoggerFactory.getLogger(CCEngineUtill.class);

    public static void main(String[] args) {
//        restartCCEngine("AT");
//        stopCCEngine();
//        startCCEngine("AT");
//        getCCEnv("CC_CENTER_JOBQUEUE");   // 获取客户端的工作路径
//        getCCEnv("CC_CENTER_JOBTEST");
//        updateCCEnv("CC_CENTER_JOBQUEUE","F:\\jobs");
//        updateCCEnv("CC_CENTER_JOBQUEUE","C:\\Users\\26372\\Documents\\Bentley\\ContextCapture Center\\Jobs");
//        C:/Users/26372/Documents/Bentley/ContextCapture Center/Jobs
//        haveDir("E:\\test\\test");
    }

    /**
     * 执行命令公用方法
     *
     * @param commond
     * @return
     */
    public static String runStartCommand(String commond,String path) {
        String TEMP_URL = System.getenv().get("TEMP");
        String CC_CENTER_URL = System.getenv().get("CC_CENTER");
        Runtime run = Runtime.getRuntime();
        String msg = null;
        try {
            String[] env = new String[3];
            env[0] = "CC_CENTER_JOBQUEUE="+path;
            env[1] = "CC_CENTER="+CC_CENTER_URL;
            env[2] = "TEMP="+TEMP_URL;
            Process process = run.exec(commond,env);
            InputStream in = process.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "GBK"));
            while (in.read() != -1) {
                msg = br.readLine();
            }
            in.close();
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }
    public static String runCommand(String commond) {
        Runtime run = Runtime.getRuntime();
        String msg = null;
        try {
            Process process = run.exec(commond);
            InputStream in = process.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "GBK"));
            while (in.read() != -1) {
                msg = br.readLine();
            }
            in.close();
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 启动引擎
     *
     * @param engineType AT -- 空三
     *                   TileProduction -- 模型
     *                   RasterProduction -- 正射
     *                   TileProduction RasterProduction -- 正射&模型
     */
    public static void startCCEngine(String engineType,String path,String ccPath) {
        String url = ccPath.replaceAll("/","\\\\");
        String furl = url.replaceAll(" ","\""+" "+"\"");
        String startcommand = "cmd /c start "+furl+"\\CCEngine.exe --type \"" + engineType +"\"";
        String havecommand = "cmd /c tasklist | findstr CCEngine.exe";
        String ishave = runCommand(havecommand);
        if (ishave == null) {
            runStartCommand(startcommand,path);
            System.out.println("启动成功");
        } else {
            System.out.println("已启动");
        }
    }

    /**
     * 停止CCEngine
     */
    public static void stopCCEngine() {
        String stopcommand = "cmd /c taskkill /f /t /im CCEngine.exe";
        String stopcommand2 = "cmd /c taskkill /f /t /im CCTask.exe";
        String havecommand = "cmd /c tasklist | findstr CCEngine.exe";
        String ishave = runCommand(havecommand);
        if (ishave != null) {
            runCommand(stopcommand);
            runCommand(stopcommand2);
            System.out.println("关闭成功");
        } else {
            System.out.println("暂无活动引擎");
        }
    }

    /**
     * 重启CCEngine
     *
     * @param engineType
     */
    public static void restartCCEngine(String engineType,String path,String ccPath) {
        String url = ccPath.replaceAll("/","\\\\");
        String furl = url.replaceAll(" ","\""+" "+"\"");
        String startcommand = "cmd /c start "+furl+"\\CCEngine.exe --type \"" + engineType +"\"";
//        String startcommand = "cmd /c start C:\\Program\" \"Files\\Bentley\\ContextCapture\" \"Center\\bin\\CCEngine.exe --type \"" + engineType+"\"";
        String stopcommand = "cmd /c taskkill /f /t /im CCEngine.exe";
        String stopcommand2 = "cmd /c taskkill /f /t /im CCTask.exe";
        String havecommand = "cmd /c tasklist | findstr CCEngine.exe";
        String ishave = runCommand(havecommand);
        if (ishave != null) {
            runCommand(stopcommand);
            runCommand(stopcommand2);
            System.out.println("关闭成功");
            runStartCommand(startcommand,path);
            System.out.println("启动成功");
        } else {
            System.out.println("暂无活动引擎");
            runStartCommand(startcommand,path);
            System.out.println("启动成功");
        }
    }

    public static void restartCCEngine2(String engineType,String path,String ccPath) {
        String url = ccPath.replaceAll("/","\\\\");
        String furl = url.replaceAll(" ","\""+" "+"\"");
        String startcommand = "cmd /c start "+furl+"\\CCEngine.exe --type \"" + engineType +"\"";
//        String startcommand = "cmd /c start C:\\Program\" \"Files\\Bentley\\ContextCapture\" \"Center\\bin\\CCEngine.exe --type \"" + engineType+"\"";
        String stopcommand = "cmd /c taskkill /f /t /im CCEngine.exe";
        String stopcommand2 = "cmd /c taskkill /f /t /im CCTask.exe";
        String havecommand = "cmd /c tasklist | findstr CCEngine.exe";
        String ishave = runCommand(havecommand);
        if (ishave != null) {
            runCommand(stopcommand);
            runCommand(stopcommand2);
            System.out.println("关闭成功");
            runStartCommand(startcommand,path);
            System.out.println("启动成功");
        } else {
            System.out.println("暂无活动引擎");
            runStartCommand(startcommand,path);
            System.out.println("启动成功");
        }
    }

    /**
     * 指定目录创建文件夹
     *
     * @param path
     */
    public static void haveDir(String path) {
        String command = "cmd /c if exist \"" + path + "\" echo true";
        String is_have = runCommand(command);
        if (is_have != null) {
            System.out.println("已有文件夹");
            return;
        } else {
//            没有，创建文件夹
            String mkdircommand = "cmd /c mkdir " + path;
            String mkdir = runCommand(mkdircommand);
            if (mkdir == null) {
                System.out.println("创建成功");
            } else {
                System.out.println("路径错误，创建失败");
            }
        }
    }

    /**
     * 获取当前CCEngine 工作路径
     *
     * @param envname
     */
    public static void getCCEnv(String envname) {
        // 在cmd中执行的命令
        String command = "cmd /c set " + envname;
        String getenv = runCommand(command);
        if (getenv == null) {
            return;
        }
        String substring = getenv.substring(getenv.indexOf(envname + "=") + envname.length() + 1);
        System.out.println("CCEnv = " + substring);
    }

    public static String getJobPath(String envname) {
        // 在cmd中执行的命令
        String command = "cmd /c set " + envname;
        String getenv = runCommand(command);
        if (getenv == null) {
            return "";
        }
        String substring = getenv.substring(getenv.indexOf(envname + "=") + envname.length() + 1);
        return substring.replaceAll("\\\\","/");
    }

    /**
     * 修改CCEngine工作路径
     *
     * @param envname
     * @param path
     */
    public static void updateCCEnv(String envname, String path){
        // 在cmd中执行的命令
        String command = "cmd /c setx " + envname + " \"" + path + "\"";
        String command2 = "cmd /c set " + envname;
        haveDir(path);
        String getenv = runCommand(command);
        System.setProperty(envname, path);
    }
    public static void callApi(String url) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        URIBuilder uri = null;
        try {
            uri = new URIBuilder(url);
        }catch (Exception e){
            e.printStackTrace();
        }
        HttpPost httpPost = new HttpPost(String.valueOf(uri));
        CloseableHttpResponse response = null;
        try {
            // 执行http get请求
            httpclient.execute(httpPost);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }
    public static List<String> runCommands(String commond) {
        Runtime run = Runtime.getRuntime();
        String msg = null;
        List<String> res = new ArrayList<>();
        try {
            Process process = run.exec(commond);
            InputStream in = process.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "GBK"));
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }
                res.add(line);
            }
            in.close();
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
}
